﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace FunctionGraph
{
    public class CompileResult
    {
        public Executable MainCode;
        public SolutionEvaluationNode SolutionEvaluationTree;
        public byte[] Serialize()
        {
            using (var ms = new MemoryStream())
            {
                using (var writer = new BinaryWriter(ms))
                {
                    MainCode.Serialize(writer);
                    SolutionEvaluationTree.Accept(new SolutionEvalTreeSerializer(writer));
                }
                return ms.ToArray();
            }
        }
    }
    public class Compiler
    {
        public static CompileResult Compile(string expression)
        {
            var expr = new Parser().Parse(expression.ToLower());
            if (expr != null)
            {
                expr.Accept(new ExponentialVisitor());
                try
                {
                    CompileResult rs = new CompileResult();
                    var code = CodeGenerator.GenerateCode(expr);
                    if (code.Instructions.Count == 0)
                        return null;
                    rs.MainCode = code;
                    var solGen = new SolutionEvaluatorVisitor();
                    rs.SolutionEvaluationTree = expr.Accept(solGen);
                    return rs;
                }
                catch (Exception)
                { }
            }
            return null;
        }
    }
}
